/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionnaires;

import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import modeles.CategorieAge;
import modeles.Produit;

/**
 *
 * @author Christian
 */
@Stateless
public class GestionnaireCategoriesAges {
    @EJB
    private GestionnaireProduits gestionnaireProduits;
    @PersistenceContext
    private EntityManager em;
    
    public void creeCategoriesDeTest() {
        CategorieAge ca = new CategorieAge(3, "http://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/PEGI_3.svg/426px-PEGI_3.svg.png");
        em.persist(ca);
        ca = new CategorieAge(7, "http://upload.wikimedia.org/wikipedia/commons/thumb/2/29/PEGI_7.svg/426px-PEGI_7.svg.png");
        em.persist(ca);
        ca = new CategorieAge(12, "http://upload.wikimedia.org/wikipedia/commons/4/44/PEGI_12.svg");
        em.persist(ca);
        ca = new CategorieAge(16, "http://upload.wikimedia.org/wikipedia/commons/8/8a/PEGI_16.svg");
        em.persist(ca);
        ca = new CategorieAge(18, "http://upload.wikimedia.org/wikipedia/commons/7/75/PEGI_18.svg");
        em.persist(ca);
    }
    
    public CategorieAge creeCategorie(int ageMinimum, String urlPhoto) {
        if(urlPhoto == null || urlPhoto.isEmpty())
            return null;
        if(getCategorieByAge(ageMinimum) != null)
            return null;
        CategorieAge ca = new CategorieAge(ageMinimum, urlPhoto);
        em.persist(ca);
        return ca;
    }
    
     public Collection<CategorieAge> getAllCategories() {
        Query q = em.createQuery("select o from CategorieAge o", CategorieAge.class);
        return q.getResultList();
    }

    public CategorieAge getCategorieById(int id) {
        Query q = em.createQuery("select o from CategorieAge o where o.id=" + id, CategorieAge.class);
        if(q.getResultList().size() <= 0) return null;
        return (CategorieAge) q.getResultList().get(0);
    }

    public CategorieAge getCategorieByAge(int ageMinimum) {
        Query q = em.createQuery("select o from CategorieAge o where o.ageMinimum=" + ageMinimum, CategorieAge.class);
        if(q.getResultList().size() <= 0) return null;
        return (CategorieAge) q.getResultList().get(0);
    }

    public void suprimeCategorieByAge(int ageMinimum) {
        CategorieAge categorieAge = getCategorieByAge(ageMinimum);
        if(categorieAge == null)
            return;
        suprimeCategorieById(categorieAge.getId());
    }

    public void suprimeCategorieById(int id) {
        CategorieAge categorieAge = getCategorieById(id);
        Collection<Produit> produits = gestionnaireProduits.getProduitsByCategorieAgeById(id);
        if(!produits.isEmpty()) return;
        em.remove(categorieAge);
    }
    
}
